<?php

namespace App\Models;

use App\Http\Controllers\Api\User\ReBateController;
use App\Http\Controllers\ApiController;
use App\Http\Models\User\UserBaseModel;
use DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

/**
 * App\Models\Order
 *
 * @property int $id
 * @property string|null $order_sn 订单号
 * @property int|null $user_id 用户id
 * @property int $order_status 订单状态 0，未确认；1，已确认；2，已取消；3，无效；4，退货；
 * @property int $shipping_status 订单派送状态 0，未发货；1，已发货；2，已收货；3，备货中
 * @property int $pay_status 支付状态；0，未付款；1，付款中；2，已付款
 * @property string|null $consignee 收货人的姓名，用户页面填写，默认取值于表user_address
 * @property string|null $country 收货人的国家，用户页面填写，默认取值于表user_address
 * @property string|null $province 收货人的省份，用户页面填写，默认取值于表user_address
 * @property string|null $city 收货人的城市，用户页面填写，默认取值于表user_address
 * @property string|null $district 收货人的地区，用户页面填写，默认取值于表user_address
 * @property string|null $address 收货人的详细地址，用户页面填写
 * @property string|null $zipcode 收货人的邮编，用户页面填写
 * @property string|null $mobile 收货人的手机
 * @property string|null $remark 备注信息
 * @property int $coupon_id 优惠券id
 * @property int $pay_id 支付方式id
 * @property string|null $pay_name 支付方式名称
 * @property float $pay_fee 订单金额
 * @property float $discount 优惠金额
 * @property float $money_paid 支付金额
 * @property int|null $add_time 订单新增时间
 * @property int|null $pay_time 订单支付时间
 * @property int|null $shipping_time 订单配送时间
 * @property int|null $finish_time 订单完成时间
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereAddTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereAddress($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereCity($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereConsignee($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereCountry($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereCouponId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereDiscount($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereDistrict($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereFinishTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereMobile($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereMoneyPaid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereOrderSn($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereOrderStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order wherePayFee($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order wherePayId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order wherePayName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order wherePayStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order wherePayTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereProvince($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereRemark($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereShippingStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereShippingTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereUserId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereZipcode($value)
 * @mixin \Eloquent
 */
class Order extends Model
{
    protected $guarded=[];
    public $table = 'orders';
    public $timestamps=false;

    public static $error;

    public $_pay_status = [
       '0'  => '未付款',
       '1'  => '付款中',
       '2'  => '已付款',
       '3'  => '申请退款中',
       '4'  => '已退款',
       '5'  => '驳回退款',
    ];

    public $ship_status = [
        '0' => '未发货',
        '1' => '已发货',
        '2' => '已收货',
        '3' => '申请退货中',
        '4' => '退货成功',
        '5' => '驳回退货',
    ];

    public $_order_status = [
        '0'  => '未确认',
        '1'  => '已确认',
        '2'  => '已取消'
    ];

    public $pay_way = [
        '0' => '微信',
        '1' => '银联',
        '2' => '余额',
    ];

    //0-不显示 1-显示
    private $button = [
        'order_detail' => 1, //订单详情
        'cancel_order' => 0, //取消订单
        'pay_now'      => 0, //立即付款
        'apply_refund' => 0, //申请退款
        'view_logistics'=> 0,//查看物流按钮
        'confirm_order' => 0, //订单确认按钮
        'evaluate_now'  => 0 ,//立即评价按钮
        'apply_shipback'=> 0,//申请退货按钮
    ];

    public $admin_button = [
        'ship_goods'     => 0,  // '发货',
        'agree_shipback' => 0,  //'同意退货',
        'reject_shipback'=> 0, //'拒绝退货',
        'agree_refund'   => 0, //'同意退款',
        'reject_refund'  => 0, //'拒绝退款',
    ];

    //admin按钮映射关系
    public $admin_button_maps = [
        'ship_goods'          => '发货',
        'agree_shipback'      => '同意退货',
        'reject_shipback'     => '拒绝退货',
        'agree_refund'        => '同意退款',
        'reject_refund'       => '拒绝退款'
    ];

    //是否查询用户的信息
    public $order_user_info = false;

    //是否查询订单优惠的金额
    public $coupon_info = false;

    /**
     *订单列表页默认15个为一页
     */
    public function admin_order_list($paginate=15,$otherCondition,$status=0)
    {
        //全部(0) 待发货(1) 已发货(2) 待支付(3) 已支付(4) 已作废(5 完成退款) 已完成(6)
        //申请退款(7)  已拒绝退款(8)
        //申请退货(9)  已拒绝退货(10)
        $query = self::query()
            ->select('user.user_name','orders.*','orders.id AS order_id','hotel.name As hotel_name')
            ->leftJoin('user','user.id','=','orders.user_id')
            ->leftJoin('hotel','hotel.hotel_id','=','orders.hotel_id')
            ->orderBy('add_time','desc');

        if(!empty($status)){
            switch ($status){
                case 3:#待付款(未付款且订单未取消)
                    $query->where('pay_status','=',0)->where('order_status','=',0);
                    break;
                case 1:#待发货(已付款，订单未确认，未发货)
                    $query->where('pay_status','=',2)->where('shipping_status','=',0);
                    break;
                case 2:#已发货(已付款，订单未确认，已发货)
                    $query->where('pay_status','=',2)->where('shipping_status','=',1);
                    break;
                case 4:#买家已付款
                    $query->where('pay_status','=',2);
                    break;
                case 6:#已完成
                    $query->where('order_status','=',1);
                    break;
                case 5:#交易作废
                    $query->where(function($query){
                        return $query ->where('order_status','=',2)->orwhere('pay_status','=','4');
                    });
                    break;
                case 7:#申请退款
                    $query->where('pay_status','=',3);
                    break;
                case 8:#拒绝退款
                    $query->where('pay_status','=',5);
                    break;
                case 9:#申请退货
                    $query->where('shipping_status','=',3);
                    break;
                case 10:#拒绝退货
                    $query->where('shipping_status','=',5);
                    break;
                default: #所有订单
                    break;
            }
        }

        if(isset($otherCondition['value']) && !empty($otherCondition['input'])){
            switch ($otherCondition['value']){
                case  0:
                case  1:
                    $query -> where('order_sn','like','%'.$otherCondition['input'].'%');
                    break;
                case 2:
                    $query -> where('mobile','like','%'.$otherCondition['input'].'%');
                    break;
                case 3:
                    $query -> where('consignee','like','%'.$otherCondition['input'].'%');
                    break;
            }
        }

        #用户筛选
        if(!empty($otherCondition['user_id'])){
            $query -> where('orders.user_id','=',$otherCondition['user_id']);
        }

        #酒店筛选
        if(!empty($otherCondition['hotel_id'])){
            $query -> where('orders.hotel_id','=',$otherCondition['hotel_id']);
        }

        #房间号筛选
        if(!empty($otherCondition['room_num'])){
            $query -> where('orders.room_num','like','%'.$otherCondition['room_num'].'%');
        }

        #时间筛选
        if(!empty($otherCondition['date_arr'])){
           $date_arr = explode(',',$otherCondition['date_arr']);
           $start_date = empty($date_arr[0]) ? null :  strtotime(strstr($date_arr[0],'GMT',true));
           $end_date = empty($date_arr[1]) ? time() :  strtotime(strstr($date_arr[1],'GMT',true));
           if(!empty($start_date)){
               $query -> where('add_time','>=',$start_date);
           }
           $query -> where('add_time','<=',$end_date);
        }

//        dd($query->toSql());
        $total_count = $query->count();

        $page = empty($otherCondition['page']) ? 1 : $otherCondition['page'];
        $offset = ($page-1) * $paginate;

        $orderList  = $query->offset($offset)->limit($paginate)->get()->toArray();
        foreach($orderList as &$order){
            $order['order_time']   = date('Y.m.d H:i:s',$order['add_time']);
            $order['pay_status']   = $this -> _pay_status[$order['pay_status']];
            $order['order_status'] = $this -> _order_status[$order['order_status']];
            $order['ship_status']  = $this -> ship_status[$order['shipping_status']];
            $order['pay_way'] = $this -> pay_way[$order['pay_id']];
            $order['ship_way'] = '快递';//统一用快递
            unset(
                $order['zipcode'],$order['remark'],
                $order['pay_name'],$order['pay_fee'],
                $order['discount'],$order['add_time'],
                $order['shipping_time'],$order['finish_time'],
                $order['refund_reason'],$order['comment_status'],
                $order['express_encode'],$order['express_company'],
                $order['express_no'],$order['express_company'],$order['id'],
                $order['pay_id']
            );
        }

        $data =  [
            'list'      => $orderList,
            'total'     => $total_count,
            'page_size' => $paginate
        ];
        return $data;
    }



    #根据订单号 获取订单数据
    public static function getOrderBaseInfoByOrderSn($order_sn)
    {

        $type = ApiController::getOrderType($order_sn);
        if ($type==1){
            $data = self::where('order_sn',$order_sn)->first();
            if(empty($data)){
                return [];
            }else{
                $data = $data->toArray();
            }
        }elseif ($type==2||$type==3){
            $data = RechargeOrder::getRechargeOrder($order_sn);
        }
        return $data;
    }

    #根据订单号 获取订单数据
    public static function getOrderBaseInfoByOrderId($orderId)
    {
        $orderModel = self::find($orderId);
        if(empty($orderModel)){
            return [];
        }
        $orderModel = $orderModel->toArray();
        $type = ApiController::getOrderType($orderModel['order_sn']);
        if ($type==1){
            $data = self::where('order_sn',$orderModel['order_sn'])->first();
            if(empty($data)){
                return [];
            }else{
                $data = $data->toArray();
            }
        }elseif ($type==2||$type==3){
            $data = RechargeOrder::getRechargeOrder($orderModel['order_sn']);
        }
        return $data;
    }

    /**订单查询接口调用的model
     * @param $condition
     */
    public function api_order_list($condition,$exclude = -1,$addSelect=[])
    {
        $common_select = [
            'order_id','orders.order_sn','consignee AS username','province','city','district','orders.user_id',
            'address','mobile','add_time as order_time','money_paid','pay_fee','pay_id',
            'ogoods.goods_number','ogoods.goods_id',
            'ogoods.goods_name','goods.bn','ogoods.goods_price',
            'pay_status','order_status','shipping_status','comment_status','express_encode','express_no'
        ];
        #公共join
        $query = DB::table('orders')
            ->select($common_select)
            ->selectRaw(DB::raw('CONCAT("",image) AS image')->getValue())
            ->leftJoin('order_goods as ogoods','ogoods.order_id','=','orders.id')
            ->leftJoin('goods','goods.goods_id','=','ogoods.goods_id')
            ->orderBy('order_time','desc');

        if(!empty($condition)){
            foreach($condition as $conditionK => $conditionV){
                if(!is_array($conditionV)){
                    $query = $query -> where($conditionK,'=',$conditionV);
                }else{
                    $query = $query -> where($conditionV[0],$conditionV[1],$conditionV[2]);
                }
            }
        }

//        $cartModel = new Cart();
//        $query = $cartModel -> _sku_info_join($query,$query);

        #order_status     订单整体状态 0，未确认；1，已确认；2，已取消（交易关闭订单 无效订单）；3，无效；
        #shipping_status  发货状态 0-未发货 1-已发货 2 已收货 3-申请退货 4-退货成功 5-驳回退货
        #pay_status       支付状态 0-未付款；1-付款中；2-已付款 3-申请退款 4-已退款 5-驳回退款
        #pay_id           支付方式 0-微信 1-银联   pay_name
        #状态迁移图   下单-生成订单-未付款(拉起支付但是未支付,此时可以取消订单或者立即付款)-已付款(此时可以退款)-未发货(此时可以退款和查看详情)-已发货(此时可以退款和退货,对于买家是待收货，此时可查看详情和物流)-确认收货(已收货-待评价)-

        #订单综合查询
        $query = $this -> _order_status_where($query,$exclude);

        #查询结果
        $result = $query -> get()->map(function($val) use($exclude){
            return (array) $val;
        })->toArray();

        $result = $this -> _pretty_order_data($result);

        return $result;
    }

    /**
     * 统计各阶段订单数量显示
     */
    public function api_order_statistic($condition)
    {
        $query = DB::table('orders')
            ->selectRaw(DB::raw('CONCAT("'.config('app.url').'",image) AS image')->getValue())
            ->join('order_goods as ogoods','ogoods.order_id','=','orders.id')
            ->join('products','products.product_id','=','ogoods.sku_id')
            ->orderBy('order_time','desc');

        if(!empty($condition)){
            foreach($condition as $conditionK => $conditionV){
                if(!is_array($conditionV)){
                    $query = $query -> where($conditionK,'=',$conditionV);
                }else{
                    $query = $query -> where($conditionV[0],$conditionV[1],$conditionV[2]);
                }
            }
        }

        return [
            'status_0_num' => $this->_order_status_where(clone $query,0)->count(),
            'status_1_num' => $this->_order_status_where(clone $query,1)->count(),
            'status_2_num' => $this->_order_status_where(clone $query,2)->count(),
            'status_3_num' => $this->_order_status_where(clone $query,3)->count(),
            'status_4_num' => $this->_order_status_where(clone $query,4)->count(),
        ];
    }

    private function parseSelect($addSelect=[],$overide=false)
    {
        $common_select = [
            'order_id','orders.order_sn','consignee AS username','province','city','district','orders.user_id',
            'address','mobile','add_time as order_time','money_paid','pay_fee','pay_id',
            'ogoods.goods_number','products.name AS goods_name','ogoods.sku_id',
            'sku_props_vals.props_id', 'sku_props_vals.props_val_id',
            'props_vals.name AS props_val_name','props.name AS props_name',
            'products.price AS sku_price','products.discount_price AS sku_discount_price','products.bn',
            'pay_status','order_status','shipping_status','comment_status','express_encode','express_no',
            'orders.coupon_id AS coupon_users_id',
            'reject_return_back','reject_refund_reason',
        ];
        if(!empty($addSelect)){
            array_push($common_select,$addSelect);
        }
        return $common_select ;
    }

    /*订单表信息优化显示
     * @param $list   array  需要格式化的列表
     * @$payload      array  需要添加到数组中的参数
     * @return array  返回格式化好的列表
     */
    private function _pretty_order_data($list)
    {
        #处理规格
        $order_new_list = [];
//        dd($list);
        foreach($list as $order){
            if(!isset($order_new_list[$order['order_id']])){
                $order['total_number'] = 0;
                //控制前端的按钮显示
                $this -> button_show($order);
                //控制后端的按钮显示
                $this -> backend_button_show($order);
                $this -> _format_order_info($order);
                $order['order_time'] = date('Y-m-d H:i:s',$order['order_time']);
                $order_new_list[$order['order_id']] = $order;
            }

            if(!isset($order_new_list[$order['order_id']]['goods_list'][$order['goods_id']])){
                $order_new_list[$order['order_id']]['goods_list'][$order['goods_id']]= [
                    'goods_name' => $order['goods_name'],
                    'goods_number' => $order['goods_number'],
                    'image'  => $order['image'],
                    'price'  => $order['goods_price'],
                ];
                $order_new_list[$order['order_id']]['total_number'] += $order['goods_number'];
            }


//            $order_new_list[$order['order_id']]['goods_list'][$order['sku_id']]['props'][] = [
//                'props_val_name'=> $order['props_val_name'],
//                'props_val_id'  => $order['props_val_id'],
//                'props_name'    => $order['props_name'],
//                'props_id'      => $order['props_id'],
//            ];

            unset(
                $order_new_list[$order['order_id']]['props_id'],
                $order_new_list[$order['order_id']]['props_val_id'],
                $order_new_list[$order['order_id']]['props_name'],
                $order_new_list[$order['order_id']]['props_id'],
                $order_new_list[$order['order_id']]['sku_price'],
                $order_new_list[$order['order_id']]['sku_discount_price'],
                $order_new_list[$order['order_id']]['sku_id'],
                $order_new_list[$order['order_id']]['props_val_name']
//                $order_new_list[$order['order_id']]['goods_list'][$order['sku_id']]['props_val_name'],
//                $order_new_list[$order['order_id']]['goods_list'][$order['sku_id']]['props_val_id'],
//                $order_new_list[$order['order_id']]['goods_list'][$order['sku_id']]['props_name'],
//                $order_new_list[$order['order_id']]['goods_list'][$order['sku_id']]['props_id']
            );
        }

        $order_new_list = array_values($order_new_list);
        array_walk($order_new_list,function(&$item,$index){
            $item['goods_list'] = array_values($item['goods_list']);
        });

        return $order_new_list;
    }

    /**根据订单状态判断订单的按钮显示
     * 订单按钮的显示
     */
    public function button_show(&$order_item)
    {
        #订单取消单
        if($order_item['order_status'] == 2){
            $this -> button['order_detail'] = 0;
            $order_item['order_status_text'] = '交易关闭';
        }else if($order_item['pay_status'] == 0 && $order_item['order_status'] == 0){
            #待付款(未付款且订单未取消),此时显示取消订单和立即付款按钮，查看详情
            $this -> button['cancel_order'] = 1;
            $this -> button['pay_now'] = 1;
            $order_item['order_status_text'] = '待付款';
        }else if($order_item['pay_status'] == 2 && $order_item['shipping_status'] == 0){
            #待发货 此时显示 查看详情 申请退款 按钮
            $this -> button['apply_refund'] = 1;
            $order_item['order_status_text'] = '待发货';
        }else if($order_item['pay_status'] == 2 && $order_item['shipping_status'] == 1){
             #待收货 此时显示 查看详情  查看物流按钮
//            $this -> button['apply_refund'] = 1;
            $this -> button['view_logistics'] = 1;
            $this -> button['confirm_order'] = 1;
            $this -> button['apply_shipback'] = 1;
            $order_item['order_status_text'] = '待收货';
        }else if($order_item['comment_status'] == 0 &&$order_item['pay_status'] == 2 && $order_item['order_status'] == 1 && $order_item['shipping_status'] == 2){
            #待评价 此时显示 查看详情 查看物流 立即评价
            $this -> button['view_logistics'] = 1;
            $this -> button['evaluate_now']   = 1;
            $order_item['order_status_text'] = '待评价';
        }else if(in_array($order_item['pay_status'],[3,4,5])){
            #退款单
            $order_item['order_status_text'] = $this->_pay_status[$order_item['pay_status']];
        }else if($order_item['order_status'] == 1 && $order_item['comment_status'] == 1){
            #成功单
            $order_item['order_status_text'] = '交易成功';
        }else if(in_array($order_item['shipping_status'],[3,4,5])){
            #退货单
            $order_item['order_status_text'] = $this -> ship_status[$order_item['shipping_status']];
        }

        $order_item['button_list'] = $this->button;
        //重置状态
        foreach($this->button as $k => &$v){
            $v = 0;
        }

        $this -> button['order_detail'] = 1;
    }

    /**后台订单按钮控制显示
     * @param $order_item
     */
    public function backend_button_show(&$order_item)
    {
        return $order_item;
        #申请退款单 显示同意和拒绝退款按钮
        if($order_item['pay_status'] == 3){
            $this -> admin_button['agree_refund'] = 1;
            $this -> admin_button['reject_refund'] = 1;
        }else if($order_item['pay_status'] == 2 && $order_item['shipping_status'] == 0){
            #待发货 显示发货按钮
            $this -> admin_button['ship_goods'] = 1;
        }else if($order_item['shipping_status'] == 3){
            #申请退货单  显示同意退货和拒绝退货按钮
            $this -> admin_button['agree_shipback'] = 1;
            $this -> admin_button['reject_shipback'] = 1;
        }

        $order_item['admin_button_list'] = $this->admin_button;
        $order_item['admin_button_maps'] = $this->admin_button_maps;
        //重置状态
        foreach($this->admin_button as $k => &$v){
            $v = 0;
        }
    }

    /**
     *
     */
    public function _format_order_info(&$order_item)
    {
        $order_item['coupon_moeny'] = 0;

        //支付方式格式化
        if(isset($order_item['pay_id'])){
            $order_item['pay_way'] = $this->pay_way[$order_item['pay_id']];
        }
        //会员信息格式化
        if(isset($order_item['pay_id'])){
            $order_item['pay_way'] = $this->pay_way[$order_item['pay_id']];
        }

        //优惠金额信息
        if($this->coupon_info){
            //如果使用了优惠券，则标记优惠的金额
            if(!empty($order_item['coupon_users_id'])){
                $order_item['coupon_moeny'] = Coupon::get_order_coupon_money($order_item['coupon_users_id'],$order_item);
            }
        }

        //查询用户信息
        if($this->order_user_info){
            //如果使用了优惠券，则标记优惠的金额
            if(isset($order_item['user_id'])){
                $user_model = User::find($order_item['user_id']);
                if(!empty($user_model)){
                    $order_item['user_info'] = [
                        'user_name' => $user_model->user_name,
                        'user_sex'  => $user_model->user_sex==1?'男':'女',
                        'user_nickname'=>$user_model->user_nickname,
                        'is_vip'    => $user_model->is_vip,
                    ];
                }

            }
        }


        if(!empty($order_item['express_no'])){
            $order_item['expree_url'] = $this->getExpressUrl($order_item['express_encode'],$order_item['express_no'],'');
        }
    }

    /**
     * 取消订单接口
     *
     */
    public function api_cancel_order($request)
    {
        $order_model = self::find($request->input('order_id'));
        if(empty($order_model)){
            self::$error = '无效的订单!';
            return false;
        }

        if($order_model->user_id != $request->input('user_id')){
            self::$error = '该用户不存在该订单!';
            return false;
        }

        //订单不是已经取消状态
        if($order_model -> order_status != 2){
            if($order_model -> pay_status != 0){
                self::$error = '该订单已付款,无法取消';
                return false;
            }
            $order_model -> order_status =  2;
            $order_model -> save();
        }

        #订单取消，恢复商品库存和sku库存
        $order_goods_list = DB::table('order_goods')->where('order_id','=',$request->input('order_id'))->get()->map(function($val){
            return (array) $val;
        })->toArray();

        foreach($order_goods_list as $sku){
            $product_model = Product::find($sku['sku_id']);
            #sku库存增加
            if(!empty($product_model)){
                $product_model -> stock += $sku['goods_number'];
                $product_model -> save();
            }

            #spu库存增加
            $spu_model = Goods::find($product_model->goods_id);
            if(!empty($spu_model)){
                $spu_model -> stock += $sku['goods_number'];
                $spu_model -> save();
            }
        }

        return true;
    }

    /**
     * 申请退款接口
     */
    public function api_apply_refund($postdata)
    {
        $order_model = self::find($postdata['order_id']);
        if(empty($order_model)){
            self::$error = '无效的订单';
            return false;
        }



        if($order_model ->user_id != $postdata['user_id']){
            self::$error = '该用户不存在该订单!';
            return false;
        }

        //查看订单是否允许退款
        if($order_model -> order_status == 1){
            self::$error = '该订单已确认，无法退款!';
            return false;
        }

        if($order_model -> order_status == 2){
            self::$error = '该订单已关闭,无法退款';
            return false;
        }

        if($order_model -> pay_status > 2){
            self::$error = '请勿重复申请退款';
            return false;
        }

        #查看该订单的付款状态是否是已付款并且是待发货
        if($order_model -> pay_status == 2 && $order_model -> shipping_status == 0){
            //可以进行给退款
            $order_model -> pay_status = 3;
            $order_model -> refund_reason = $postdata['refund_reason'];
            $order_model -> save();
            return true;
        }


        self::$error  = '该订单不满足退款条件!';
        return false;
    }

    /**确认收货接口
     * @param $postdata
     */
    public function api_confirm_ship($postdata)
    {
        $order_model = self::find($postdata['order_id']);
        if(empty($order_model)){
            self::$error = '无效的订单!';
            return false;
        }

        if($order_model->user_id != $postdata['user_id']){
            self::$error = '该用户不存在该订单!';
            return false;
        }

        //判断是否可以确认收货
        if($order_model -> shipping_status == 0){
            self::$error = '该订单未发货';
            return false;
        }

        //已经提交申请 无需提交
        if($order_model -> shipping_status == 2){
            self::$error = '请不要重复提交确认收货请求';
            return false;
        }

        $user = UserBaseModel::find($order_model->user_id);
        $vip_limit = SystemConfig::getConfValByConfKey('recharge_limit')['conf_val'];
        if ($user->is_vip !=1&&$order_model->pay_fee>$vip_limit){
            UserBaseModel::updateUser($user->id,['is_vip'=>1]);
        }
        self::query()->where('id','=',$postdata['order_id'])->update(['shipping_status'=>2,'order_status'=>1]);
        return true;
    }


    public static function getOrderInfo()
    {
        $data = self::query()
            ->join('distribution','distribution.order_sn','=','orders.order_sn')
            ->join('user','user.id','=','orders.user_id')
            ->select('user.user_name','orders.order_sn','orders.user_id','orders.money_paid','distribution.level','distribution.total_money','distribution.rate','distribution.created_at')
            ->get();
        if (empty($data)){
            return [];
        }else{
            return $data->toArray();
        }
        return $data;
    }

    /**
     * @param $request  \Illuminate\Http\Request
     * @return mixed
     */
    public function api_make_order($request)
    {
        if(!($userInfoArr = User::getUserInfoByOpenId($request->open_id))){
            self::$error = '该用户未绑定open_id';
            return false;
        }
        //订单基础信息,from_type=0 来源于商品立即结算  from_type=1来源于购物车结算
        $order = [
            'order_sn'       => ApiController::get_order_sn(1),
            'user_id' 		 => $userInfoArr['id'],
            'order_status'   => 0,
            'shipping_status'=> 0,
            'mac'            => $request -> mac,
            'pay_status' 	 => 0,
            'consignee'		 => $request->consignee ??'',
            'country'		 => $request->country ??'中国',
            'province'		 => $request->province ??'',
            'city'			 => $request->city ??'',
            'district'		 => $request->district ??'',
            'address'		 => $request->address ??'',
            'zipcode'		 => $request->zipcode ??'',
            'mobile'		 => $request->mobile ?? '',
            'remark'		 => $request->remark ?? '',
            'coupon_id'  	 => $request->coupon_id ?? 0,
            'pay_fee'		 => $request->pay_fee,
            'discount'		 => $request->discount ?? 0,
            'money_paid'	 => $request->money_paid,
            'add_time'		 => time(),
            'pay_id'         => isset($request->pay_id)?$request->pay_id:0
        ];


        try{
            #开启事务
            DB::beginTransaction();

            #检查该mac是否已经绑定酒店
            $Machine = MachineModel::apiGetMachineByMac($request->mac);
            if(empty($Machine)){
                self::$error = '该mac号'.$request->mac.'未绑定酒店!';
                return false;
            }
            $order['hotel_id'] = $Machine['hotel_id'];
            $order['room_num'] = $Machine['room_num'];
            $order['machine_id'] = $Machine['machine_id'];

            #检查商品的库存，是否下架,并且将商品的库存和sku库存减少
            $this -> check_sku_and_update($Machine['hotel_id'],$request->goods);

            #如果订单来自于购物车结算，则将该用户的购物车中的商品清除
            if($request->from_type == 1){
                $cartModel = new Cart();
                $cartModel -> deleteFromCartWhenMakeOrder($request->goods,$request->user_id);
            }

            #生成订单号
            $order_id = DB::table('orders')->insertGetId($order);

            #插入订单商品详情表
            $this -> insert_into_orderGoods($request->goods,$order_id);

            #酒店分成记录插入
            $reBateController = new ReBateController();
            $reBateController -> RebateByUid($userInfoArr['id'],$order['order_sn'],$order['money_paid'],$Machine['hotel_id']);
            DB::commit();
            return $order['order_sn'];
        }catch(\Exception $e){
            self::$error = $e -> getMessage();
            DB::rollBack();
            return false;
        }
    }

    /**检查该sku_id的商品是否可以购买,如果可以购买则将库存减少
     * @param $goods_arr array  形如[['amount'=>1,'sku_id'=>2],['amount'=>22,'sku_id'=>3]]
     */
    private function check_sku_and_update($hotel_id,$goods_arr)
    {
        $goods_id_arr = $goods_arr['goods_id'];
        $grid_id  = $goods_arr['box_id'];

        if(!is_array($goods_id_arr)){
            $goods_arr = [$goods_id_arr];
        }

        $length_of_goods_arr = count($goods_arr);
        foreach($goods_arr as $goods_id){
            #获取该酒店的商品详情信息
            $sku_model = HotelGoods::getHotelGoodsInfo($hotel_id,$goods_id);

            #没有根据酒店id和goods_id的信息
            if(empty($sku_model)){
                throw new \Exception('您购买的商品已经不存在了，请重新选择商品下单');
            }

            #如果该商品被删除了，则无法购买
            if($sku_model['disabled'] == 1){
                throw new \Exception('商品 : '.$sku_model['goods_name'].'已删除，请重新下单!');
            }

            #检查该商品是否已经下架
            if($sku_model['marketable'] == 0){
                throw new \Exception('商品 : '.$sku_model['goods_name'].'已下架，请重新下单!');
            }

            #检查该酒店商品是否已经运用了模板
            if($sku_model['is_on_sale'] == 0){
                throw new \Exception('商品 : '.$sku_model['goods_name'].'尚未在该酒店出售，请重新选择商品下单!');
            }

            #检查该商品的库存是否充足
            if($sku_model['hotel_stock'] < 1){
                throw new \Exception('商品 : '.$sku_model['goods_name'].'的酒店库存不足!');
            }

            #减少该商品的酒店库存 因为前端没有对原始订单的操作功能，所以这部分减少库存的操作注释掉了
//            $hotel_goodsModel = HotelGoods::$model;
//            $hotel_goodsModel -> stock -= 1;
//            if(!$sku_model->save()){
//                throw new \Exception('商品'.$sku_model['goods_name'].'库存更新失败'.'(sku)');
//            }

            #将格子商品的货柜状态变更为无货，因为前端没有对原始订单的操作功能，所以这部分减少库存的操作注释掉了
//            $spu_model-> stock -= $sku['amount'];
//            if(!$spu_model->save()){
//                throw new \Exception('商品'.$sku_model->name.'库存更新失败'.'(spu)');
//            }
        }
    }

    /**将商品信息插入订单商品详情表
     * @param $goods    array  形如[['amount'=>1,'sku_id'=>2],['amount'=>22,'sku_id'=>3]]
     * @param $order_id int  订单id
     */
    private function insert_into_orderGoods($goods,$order_id)
    {
        $goods_id_arr = $goods['goods_id'];
        $grid_id  = $goods['box_id'];
        if(!is_array($goods_id_arr)){
            $goods_id_arr = [$goods_id_arr];
        }

        $goods_arr = [];
        foreach ($goods_id_arr as $key => $val){
            $goods_arr[$key]['order_id'] = $order_id;
            $goods_arr[$key]['goods_number'] = 1;
            $goods_arr[$key]['sku_id'] = 0; //没有sku_id

            //goods_id和goods_name暂时从数据库中获取
            $sku_model = Goods::find($val);
            $goods_arr[$key]['goods_name'] = $sku_model->goods_name ;
            $goods_arr[$key]['goods_id']   = $val;
            $goods_arr[$key]['market_price'] = empty($sku_model -> discount_price) ? $sku_model -> price : $sku_model -> discount_price;
            $goods_arr[$key]['goods_price'] = $sku_model -> price;
        }
        if(!DB::table('order_goods')->insert($goods_arr)){
            throw new \Exception('商品订单生成失败!');
        }
    }


    public static function send($input)
    {
        $input['shipping_status'] = 1;
        $input                    = ApiController::createData('orders',$input);
        $flag                     = Order::where('order_sn',$input['order_sn'])->update($input);
        return $flag;
    }

    public static function complete($input)
    {
        $input                  = ApiController::createData('orders',$input);
        $flag                   = Order::where('order_sn',$input['order_sn'])->update($input);
       return $flag;
    }



    public function getExpressUrl($express_encode,$express_no,$callbackurl='')
    {
        $url = "https://m.kuaidi100.com/index_all.html?type={$express_encode}&postid={$express_no}";
        return $url;
    }

    /**申请退货
     * @param $postData
     */
    public function api_apply_shipback($postData)
    {
        $orderModel = self::getOrderBaseInfoByOrderId($postData['order_id']);
        if(empty($orderModel)){
            self::$error = '无效的订单';
            return false;
        }

        if($postData['user_id'] != $orderModel['user_id']){
            self::$error = '该用户不存在该订单!';
            return false;
        }

        #检验是否已经提交了退货申请
        if($orderModel['shipping_status'] > 2){
            self::$error = '请勿重复提交退货申请';
            return false;
        }

        #检验是否满足退货申请的条件(已付款 已发货 订单未确认)
//        dd($orderModel['pay_status'],$orderModel['shipping_status'],$orderModel['order_status']);
        if(!($orderModel['pay_status'] == 2 && $orderModel['shipping_status'] == 1 && $orderModel['order_status'] == 0)){
            self::$error = '该订单不满足退货条件!';
            return false;
        }

        #进行退货申请操作
        $res =  self::query()->where('id','=',$postData['order_id'])->update([
            'shipping_status' => 3, 'return_back'=>$postData['reason'],
        ]);

        if(!$res){
            self::$error ='申请退货失败，请稍候再试!';
            return false;
        }
        return true;
    }

    /**订单状态公共where
     * @param $query  \Illuminate\Database\Query\Builder
     * @param $exclude
     * @return   \Illuminate\Database\Query\Builder
     */
    private function _order_status_where($query,$exclude)
    {
        switch ($exclude){
            case 0: #待付款(未付款且订单未取消)
                $query->where('pay_status','=',0)->where('order_status','=',0);
                break;
            case 1: #待发货(已付款，订单未确认，未发货)
                $query->where('pay_status','=',2)->where('shipping_status','=',0);
                break;
            case 2: #待收货(已付款，订单未确认，已发货)
                $query->where('pay_status','=',2)->where('shipping_status','=',1);
                break;
            case 3:#待评价(已付款，订单未确认，已收货)
                $query->where('pay_status','=',2)->where('comment_status','=',0)->where('order_status','=',1)->where('shipping_status','=',2);
                break;
            case 4:#退款或退货售后
                $query->where(function($query){
                    $query->whereIn('pay_status',[3,4,5])
                        ->orwhere(function($query){
                            $query -> whereIn('shipping_status',[3,4,5]);
                        });
                });
                break;
            default: #所有订单
                break;
        }

        return $query;
    }

    #酒店所属订单
    #post变量
    public function api_hotel_order_list($post)
    {

        #公共join
        $query = self::query()
            ->from('orders')
            ->select(
                'order_id','orders.order_sn','orders.hotel_id','orders.machine_id',
                'add_time as order_time','money_paid','pay_fee',
                'ogoods.goods_number','goods.goods_name',
                'pay_status','order_status',
                'hotel.name AS hotel_name','machine.machine_name',
                'machine.room_num'
            )
            ->selectRaw(DB::raw('CONCAT("'.config('').'",image) AS image')->getValue())
            ->leftJoin('order_goods as ogoods','ogoods.order_id','=','orders.id')
            ->orderBy('order_time','desc')
            ->leftJoin('hotel_owners_apply as hoa','hoa.hotel_id','=','orders.hotel_id')
            ->leftJoin('hotel','hotel.hotel_id','=','orders.hotel_id')
            ->leftJoin('machine','machine.machine_id','=','orders.machine_id')
            ->leftJoin('goods','goods.goods_id','=','ogoods.goods_id')
            ->where('hoa.status','=',1)
            ->where('pay_status','=',2);

        foreach($post as $field => $v){
            $query -> where($field,'=',$v);
        }

        $list = $query -> get() -> all();
        $order_new_list = [];
        foreach ($list as &$order){
            $order['order_time'] = date('Y-m-d H:i',$order['order_time']);
            if(!isset($order_new_list[$order['order_id']])){
                $order['goods_num'] = 0;
                $order_new_list[$order['order_id']] = $order;
            }

            if(!isset($order_new_list[$order['order_id']]['goods_list'][$order['goods_id']])){
                $order_new_list[$order['order_id']]['goods_list'][$order['goods_id']]= [
                    'goods_name'   => $order['goods_name'],
                    'goods_number' => $order['goods_number'],
                    'sku_id'       => $order['sku_id'],
                    'image'        => $order['image'],
                ];
                $order_new_list[$order['order_id']]['total_number'] += $order['goods_number'];
            }
        }
        $order_new_list = array_values($order_new_list);
        array_walk($order_new_list,function(&$item,$index){
            $item['goods_list'] = array_values($item['goods_list']);
        });
        return $order_new_list;

    }




}
